﻿using System;
using System.Collections.Generic;
using System.Xml;
using System.ComponentModel;

namespace DotNetNuke.Modules.PowerShell.Services.Rss
{
	public class RssContent
	{
		#region Private Properties
		private string _path;
		private XmlDocument _rssDoc;

		private IList<RssItem> _items;
		#endregion

		#region Public Properties
		public string Title { get; set; }
		public string Link { get; set; }
		public string Description { get; set; }
		public DateTime PublishDate { get; set; }

		[ReadOnly(true)]
		public IList<RssItem> Items
		{
			get
			{
				return _items;
			}
		}
		#endregion

		#region Constructors
		public RssContent(string path)
		{
			_path = path;
			_items = new List<RssItem>();
			EnsureLoadContent();
		}
		#endregion

		#region Private Methods
		private void EnsureLoadContent()
		{
			if (_rssDoc == null)
			{
				_rssDoc = new XmlDocument();
				_rssDoc.Load(_path);
				LoadContent();
			}
		}

		private void LoadContent()
		{
			LoadSummary();
			LoadItems();
		}

		private void LoadSummary()
		{
			if (_rssDoc.SelectSingleNode("rss/channel/title") != null)
			{
				this.Title = _rssDoc.SelectSingleNode("rss/channel/title").InnerText;
			}
			if (_rssDoc.SelectSingleNode("rss/channel/link") != null)
			{
				this.Link = _rssDoc.SelectSingleNode("rss/channel/link").InnerText;
			}
			if (_rssDoc.SelectSingleNode("rss/channel/description") != null)
			{
				this.Description = _rssDoc.SelectSingleNode("rss/channel/description").InnerText;
			}
			if (_rssDoc.SelectSingleNode("rss/channel/pubDate") != null)
			{
				this.PublishDate = Convert.ToDateTime(_rssDoc.SelectSingleNode("rss/channel/pubDate").InnerText);
			}
		}

		private void LoadItems()
		{
			foreach (XmlNode node in _rssDoc.SelectNodes("rss/channel/item"))
			{
				RssItem item = new RssItem();
				item.Title = node.SelectSingleNode("title").InnerText;
				item.Link = node.SelectSingleNode("link").InnerText;
				if (node.SelectSingleNode("category") != null)
				{
					item.Category = node.SelectSingleNode("category").InnerText;
				}
				if (node.SelectSingleNode("description") != null)
				{
					item.Description = node.SelectSingleNode("description").InnerText;
				}
				if (node.SelectSingleNode("pubDate") != null)
				{
					item.PublishDate = Convert.ToDateTime(item.Category = node.SelectSingleNode("pubDate").InnerText);
				}
				_items.Add(item);
			}
		}
		#endregion

		#region Public Methods
		#endregion
	}
}
